cmake_minimum_required(VERSION 3.16)

project(GateServer VERSION 0.1.0 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

find_package(Boost 1.70 REQUIRED COMPONENTS system filesystem)
find_package(JsonCpp CONFIG REQUIRED)
find_package(Protobuf REQUIRED)
find_package(gRPC CONFIG REQUIRED)


# 生成 protobuf 和 gRPC 代码
set(PROTO_FILES
    ${CMAKE_CURRENT_SOURCE_DIR}/message.proto
)

set(PROTO_GENERATED_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated)
file(MAKE_DIRECTORY ${PROTO_GENERATED_DIR})

foreach(PROTO_FILE ${PROTO_FILES})
    get_filename_component(PROTO_NAME ${PROTO_FILE} NAME_WE)
    list(APPEND PROTO_SRCS
        ${PROTO_GENERATED_DIR}/${PROTO_NAME}.pb.cc
        ${PROTO_GENERATED_DIR}/${PROTO_NAME}.grpc.pb.cc
    )
    list(APPEND PROTO_HDRS
        ${PROTO_GENERATED_DIR}/${PROTO_NAME}.pb.h
        ${PROTO_GENERATED_DIR}/${PROTO_NAME}.grpc.pb.h
    )
endforeach()

add_custom_command(
    OUTPUT ${PROTO_SRCS} ${PROTO_HDRS}
    COMMAND protobuf::protoc
        --proto_path=${CMAKE_CURRENT_SOURCE_DIR}
        --cpp_out=${PROTO_GENERATED_DIR}
        --grpc_out=${PROTO_GENERATED_DIR}
        --plugin=protoc-gen-grpc=$<TARGET_FILE:gRPC::grpc_cpp_plugin>
        ${PROTO_FILES}
    DEPENDS ${PROTO_FILES}
    COMMENT "Generating protobuf and gRPC sources"
    VERBATIM
)

add_executable(GateServer
    src/GateServer.cpp
    src/CServer.cpp
    src/HttpConnection.cpp
    src/LogicSystem.cpp
    src/ConfigMgr.cpp
    ${PROTO_SRCS}
)

target_include_directories(GateServer 
    PRIVATE 
        include
        ${PROTO_GENERATED_DIR}
)

target_link_libraries(GateServer
    PRIVATE
        Boost::system
        Boost::filesystem
        protobuf::libprotobuf
        gRPC::grpc++
)

if(TARGET JsonCpp::JsonCpp)
    target_link_libraries(GateServer PRIVATE JsonCpp::JsonCpp)
elseif(TARGET jsoncpp_lib)
    target_link_libraries(GateServer PRIVATE jsoncpp_lib)
else()
    message(FATAL_ERROR "JsonCpp target not found; expected JsonCpp::JsonCpp or jsoncpp_lib")
endif()

if(WIN32)
    target_link_libraries(GateServer PRIVATE ws2_32)
endif()

configure_file(config.ini config.ini COPYONLY)
